use tauri::{Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem};
use crate::base::ServerError;
use crate::db::model::group::{Group, list_group};
use crate::db::model::operation::{list_operation, Operation, delete_operations, add_operations, CreateOperation};
use crate::task::start_work;
use tauri::{CustomMenuItem};


#[tauri::command]
async fn load_groups() -> Result<Vec<Group>, ServerError> {
    list_group()
        .await
}

#[tauri::command]
async fn load_operations(group_id:i32) -> Result<Vec<Operation>, ServerError> {
    list_operation(group_id)
        .await
}

#[tauri::command]
async fn del_operation(operation_id:i32) -> Result<bool, ServerError> {
    delete_operations(operation_id)
        .await
}

#[tauri::command]
async fn add_operation(operation: CreateOperation) -> Result<bool, ServerError> {
    add_operations(operation)
        .await
}

#[tauri::command]
async fn start_task(group_id:i32,is_loop:bool) -> Result<(), ServerError> {
    start_work(group_id,is_loop)
        .await
}

pub fn tauri_start() {
    let hide = CustomMenuItem::new("hide", "隐藏");
    let show = CustomMenuItem::new("show", "显示");
    let tray_menu = SystemTrayMenu::new()
        .add_item(hide)
        .add_native_item(SystemTrayMenuItem::Separator)
        .add_item(CustomMenuItem::new("stop", "暂停"))
        .add_native_item(SystemTrayMenuItem::Separator)
        .add_item(CustomMenuItem::new("resume", "继续"))
        .add_native_item(SystemTrayMenuItem::Separator)
        .add_item(show);
    let tray = SystemTray::new().with_menu(tray_menu);
    tauri::Builder::default()
        .on_system_tray_event(|app, event| {
            match event {
               SystemTrayEvent::MenuItemClick {id,..}=>{
                   match id.as_str() {
                       "hide" => {
                           #[cfg(target_os = "macos")]
                           app.hide().unwrap();
                       }
                       "show" => {
                           #[cfg(target_os = "macos")]
                           app.show().expect("没有窗口");
                       }
                       _ => {}
                   }
               }
                _ => {}
            }
        })
        .invoke_handler(tauri::generate_handler![load_groups,load_operations,start_task,del_operation,
        add_operation])
        .system_tray(tray)
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}